//
//  ChildViewController.m
//  PAXY365Teacher
//
//  Created by Sunny Tong on 15/7/29.
//  Copyright (c) 2015年 新疆大德小蜜蜂通信技术有限公司 All rights reserved.
//

#import "ChildViewController.h"

#import "CourseListViewController.h"


#import "Config.h"
#import "Common.h"
#import "DataSource.h"
#import "AHReach.h"

#import <ShareSDK/ShareSDK.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface ChildViewController ()

@end

@implementation ChildViewController
@synthesize scrollView;
@synthesize btnPost;
@synthesize btnTeacherType1;
@synthesize btnTeacherType2;
@synthesize btnCourse;

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear: animated];
    
    if ([UIScreen mainScreen].bounds.size.height > 480.0f) {
        
        scrollView.contentSize = CGSizeMake(320,1000);
    }
    else{
        scrollView.contentSize = CGSizeMake(320,1000 + 100);
    }

    NSString *getSelectTeacherType = nil;
    NSString *getTeacherCourse = nil;
    NSString *getTempTeacherCourse = nil;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (defaults){
        getSelectTeacherType = [defaults objectForKey:@"cloudin_365paxy_teacher_type"];
        getTeacherCourse = [defaults objectForKey:@"cloudin_365paxy_selected_coursename"];
        getTempTeacherCourse = [defaults objectForKey:@"cloudin_365paxy_selectedtemp_coursename"];
        if (getTempTeacherCourse.length==0) {
            getCourse = getTeacherCourse;
            [btnCourse setTitle:getTeacherCourse forState:UIControlStateNormal];
        }
        else{
            getCourse = getTempTeacherCourse;
            [btnCourse setTitle:getTempTeacherCourse forState:UIControlStateNormal];
        }
        
        if ([getSelectTeacherType isEqualToString:@"1"]) {
            //任课老师
            [btnTeacherType1 setBackgroundImage:[UIImage imageNamed:@"icon_unchecked.png"] forState:UIControlStateNormal];
            [btnTeacherType2 setBackgroundImage:[UIImage imageNamed:@"icon_checked.png"] forState:UIControlStateNormal];
            getTeacherType = @"1";
        }
        else if([getSelectTeacherType isEqualToString:@"2"]){
            //班主任
            [btnTeacherType1 setBackgroundImage:[UIImage imageNamed:@"icon_checked.png"] forState:UIControlStateNormal];
            [btnTeacherType2 setBackgroundImage:[UIImage imageNamed:@"icon_unchecked.png"] forState:UIControlStateNormal];
            getTeacherType = @"2";
        }
        else{
            //默认任课老师
            [btnTeacherType1 setBackgroundImage:[UIImage imageNamed:@"icon_unchecked.png"] forState:UIControlStateNormal];
            [btnTeacherType2 setBackgroundImage:[UIImage imageNamed:@"icon_checked.png"] forState:UIControlStateNormal];
            getTeacherType = @"1";
        }
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = SubBgColor;
    
    //自定义NavgationBar标题
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(150, 0, 200, 44);
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.textColor = [UIColor whiteColor];
    //titleLabel.shadowColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.text = @"绑定教师";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    //关闭
    UIImage *logoImage = [UIImage imageNamed: @"icon_back.png"];
    UIView *containingLogoView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, logoImage.size.width, logoImage.size.height)] autorelease];
    UIButton *logoUIButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [logoUIButton setImage:logoImage forState:UIControlStateNormal];
    logoUIButton.frame = CGRectMake(0, 0, logoImage.size.width, logoImage.size.height);
    [logoUIButton addTarget:self action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
    [containingLogoView addSubview:logoUIButton];
    UIBarButtonItem *containingLogoButton = [[[UIBarButtonItem alloc] initWithCustomView:containingLogoView] autorelease];
    self.navigationItem.leftBarButtonItem = containingLogoButton;
    
    //一定要记得声明代理协议，否则不起作用
    scrollView.delegate = self;

}

//关闭或返回
- (void)closeView
{
    //self.navigationController.navigationBarHidden = TRUE;
    [self.navigationController popViewControllerAnimated:YES]; //back
    
    //[self dismissViewControllerAnimated:YES completion:^{
    //TODO
    //}];
}


- (IBAction) btnTeacherType1Pressed: (id) sender
{
    getTeacherType = @"2";
    
    [btnTeacherType1 setBackgroundImage:[UIImage imageNamed:@"icon_checked.png"] forState:UIControlStateNormal];
    [btnTeacherType2 setBackgroundImage:[UIImage imageNamed:@"icon_unchecked.png"] forState:UIControlStateNormal];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:getTeacherType forKey:@"cloudin_365paxy_teacher_type"];
}

- (IBAction) btnTeacherType2Pressed: (id) sender
{
    getTeacherType = @"1";
    
    [btnTeacherType1 setBackgroundImage:[UIImage imageNamed:@"icon_unchecked.png"] forState:UIControlStateNormal];
    [btnTeacherType2 setBackgroundImage:[UIImage imageNamed:@"icon_checked.png"] forState:UIControlStateNormal];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:getTeacherType forKey:@"cloudin_365paxy_teacher_type"];
}


//选择课程
- (IBAction) btnSelectCoursePressed: (id) sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:nil forKey:@"cloudin_365paxy_selected_courseid"];
    [defaults setObject:nil forKey:@"cloudin_365paxy_selected_coursename"];
    [defaults setObject:nil forKey:@"cloudin_365paxy_selectedtemp_coursename"];
    
    CourseListViewController *nextController = [CourseListViewController alloc];
    nextController.setTitle = @"选择科目";
    [nextController sendGetDatas];
    nextController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:nextController animated:YES];
}


//提交
- (IBAction) btnUpdatePostPressed: (id) sender
{
    btnPost.enabled = FALSE;
    [self checkUpdateData];
}

//
-(void)checkUpdateData
{
    AHReach *reach = [AHReach reachForDefaultHost];
    if([reach isReachableViaWWAN] || [reach isReachableViaWiFi] || [reach isReachable]){
        
        if(getTeacherType==nil){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                            message:@"请选择教师类别"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            //获得焦点
            //[txtNickName becomeFirstResponder];
            btnPost.enabled = TRUE;
        }
        else if(getCourse==nil)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                            message:@"请选择科目"
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            btnPost.enabled = TRUE;
            
        }
        else{
            
            loadingView = [[GPRoundView alloc] initWithFrame:CGRectMake(100, 200, 130, 130)];
            [loadingView starRun];
            [self.view addSubview:loadingView];
            
            //[self updateUsersDetails];
            [NSThread detachNewThreadSelector:@selector(updateUsersDetails) toTarget:self withObject:nil];
        }
        
    }
    else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                        message:@"网络连接失败"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        btnPost.enabled = TRUE;
    }
}



//更新用户信息
- (void)updateUsersDetails
{

    @try {
        
        NSString *getUserID = nil;
        NSString *getCourseID = nil;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if (defaults){
            
            getUserID = [defaults objectForKey:@"cloudin_365paxy_uid"];
            getCourseID = [defaults objectForKey:@"cloudin_365paxy_selected_courseid"];
        }

        NSString *urlString = [NSString stringWithFormat:@"%@?platform=iOS&uid=%@&ttype=%@&tcourse=%@",UpdateTeacherInfoUrl,getUserID,getTeacherType,getCourseID];
        urlString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                        (CFStringRef)urlString,
                                                                        NULL,
                                                                        NULL,
                                                                        kCFStringEncodingUTF8);
        NSLog(@"URL=%@",urlString);
        NSDictionary *loginDict = [[DataSource fetchJSON:urlString] retain];
        NSArray *loginStatus = [loginDict objectForKey:@"Results"];
        NSLog(@"Count=%lu",(unsigned long)[loginStatus count]);
        for (int i = 0; i < [loginStatus count]; i ++) {
            
            NSDictionary *statusDict = [loginStatus objectAtIndex:i];
            NSString *getStatus = [statusDict objectForKey:@"Status"];
            
            NSLog(@"Status=%@",getStatus);
            if ([getStatus isEqualToString:@"1"]) {
                
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setObject:@"4" forKey:@"cloudin_365paxy_message_me"];
                [defaults setObject:getTeacherType forKey:@"cloudin_365paxy_teacher_type"];
                [defaults setObject:getCourse forKey:@"cloudin_365paxy_selected_coursename"];
                [self closeView];
                
            }
            else {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒"
                                                                message:@"更新失败"
                                                               delegate:self
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        
    }
    @catch (NSException * e) {
        NSLog(@"Exception: %@", e);
        return;
    }
    
    btnPost.enabled = TRUE;
    [loadingView stopRun];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
